<template>
  <view class="loan-form-container">
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        <text>返回</text>
      </view>
      <view class="header-title">创建借条</view>
      <view class="header-right"></view>
    </view>
    
    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 借款方/出借方 -->
      <view class="form-item" @click="goToCounterparty">
        <view class="form-label">借款方</view>
        <view class="form-input-wrapper">
          <div class="form-input" :style="{color: formData.borrowerName ? '#333' : 'grey'}">{{ formData.borrowerName ? formData.borrowerName : "请填写借款方" }}</div>
          <view class="arrow-icon">
            <u-icon name="arrow-right" color="#ccc" size="24"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 欠款金额 -->
      <view class="form-item">
        <view class="form-label">欠款金额</view>
        <view class="form-input-wrapper">
          <input class="form-input" placeholder="请填写欠款金额" type="digit" v-model="formData.amount" />
          <view class="unit">元</view>
        </view>
      </view>
      
      <!-- 还款方式 -->
      <view class="form-item">
        <view class="form-label">还款方式</view>
        <view class="form-input-wrapper">
          <!-- <input class="form-input" placeholder="一次性还本付息" v-model="formData.repaymentType" disabled />
           -->
          <picker @change="bindPickerChange" :value="formData.repaymentType" :range="array" range-key="name">
              <view class="form-input">{{array[formData.repaymentType].name}}</view>
          </picker>
          <view class="arrow-icon">
            <u-icon name="arrow-right" color="#ccc" size="24"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 年化利率 -->
      <view class="form-item">
        <view class="form-label">年化利率</view>
        <view class="form-input-wrapper">
          <input class="form-input" placeholder="0" type="digit" v-model="formData.interestRate" />
          <view class="unit">%</view>
        </view>
      </view>
      
      <!-- 起始日期 -->
      <view class="form-item" v-if="formData.repaymentType == 0">
        <view class="form-label">起始日期</view>
        <view class="form-input-wrapper">
          <text class="form-input">{{ formData.startDate }}</text>
          <view class="arrow-icon">
            <u-icon name="calendar" color="#ccc" size="24"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 还款日期 -->
      <view class="form-item" @click="showEndCalendar = true" v-if="formData.repaymentType == 0">
        <view class="form-label">还款日期</view>
        <view class="form-input-wrapper">
          <text class="form-input">{{ formData.lumpSumFormReqVO.repaymentDate }}</text>
          <view class="arrow-icon">
            <u-icon name="calendar" color="#ccc" size="24"></u-icon>
          </view>
        </view>
      </view>

      <!-- 分期期数 -->
      <view class="form-item" v-if="formData.repaymentType == 1">
        <view class="form-label">分期期数</view>
        <view class="form-input-wrapper">
          <input class="form-input" placeholder="请填写分期期数" type="digit" v-model="formData.installmentFormReqVO.installmentCount" />
          <view class="unit">期</view>
        </view>
      </view>

      <view class="form-item" v-if="formData.repaymentType == 1">
        <view class="form-label">每期时长</view>
        <view class="form-input-wrapper">
          <input class="form-input" placeholder="请填写每期时长" type="digit" v-model="formData.installmentFormReqVO.installmentDays" />
          <view class="unit">天</view>
        </view>
      </view>
    </view>
    
    <!-- 欠条原因 -->
    <view class="reason-section">
      <view class="section-title">欠条原因</view>
      
      <view class="reason-options">
        <view 
          v-for="(reason, index) in reasons" 
          :key="index" 
          class="reason-tag" 
          :class="{ active: formData.loanReasonId === reason.id }"
          @click="selectReason(reason.id)"
        >
          {{ reason.name }}
        </view>
      </view>
      
      <view class="reason-input">
        <textarea 
          placeholder="点击输入更详细的欠条原因" 
          v-model="formData.loanDetail"
          class="detailed-reason"
        ></textarea>
      </view>
    </view>
    
    <!-- 下一步按钮 -->
    <view class="next-btn" @click="nextStep">下一步</view>

    
    <!-- 日历组件 - 还款日期 -->
    <u-calendar
      :show="showEndCalendar"
      :mode="calendarMode"
      :min-date="maxStartDate"
      :monthNum="12"
      color="#1989fa"
      @confirm="confirmEndDate"
      @close="showEndCalendar = false"
    ></u-calendar>
  </view>
</template>

<script>
import { getLoanReason, createContract } from '@/api/user'
export default {
  data() {
    const currentDate = new Date();
    const currentTimestamp = currentDate.getTime();
    
    // 计算最大日期（10年后）
    const maxDate = new Date();
    maxDate.setFullYear(maxDate.getFullYear() + 10);
    
    return {
      currentDate: this.formatDate(currentDate),
      reasons: [],
      array: [{name:'一次性还本付息'},{name: '分期还款'}],
      formData: {
        "startDate": this.getDateString(new Date()),
        "creatorRole": "lender",
        "borrowerName": "",
        "borrowerIdCard": "",
        "amount": "",
        "interestRate": 0,
        "repaymentType": 0,
        "loanReasonId": "",
        "lumpSumFormReqVO": {
          "repaymentDate": ""
        },
        "installmentFormReqVO": {
          "installmentCount": 0,
          "installmentDays": 0
        }
      },
      // 日历组件相关
      calendarMode: 'single',
      showEndCalendar: false,
      maxEndDate: this.getDateString(maxDate),
      maxStartDate: this.getDateString(currentDate)
    }
  },
  onLoad(options) {
    if (options.realName) {
      this.formData.borrowerName = options.realName
    }
    if (options.idCard) {
      console.debug(options.idCard)
      this.formData.borrowerIdCard = options.idCard
    }
    getLoanReason().then(res => {
      console.debug(res)
      this.reasons = res.data.data
    })
  },
  methods: {
    bindPickerChange: function(e) {
      this.formData.repaymentType =  e.detail.value
    },
    goBack() {
      uni.navigateBack();
    },
    
    goToCounterparty() {
      uni.navigateTo({
        url: '/pages/loan/counterparty'
      });
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}/${month}/${day}`;
    },
    
    getDateString(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    selectReason(reason) {
      this.formData.loanReasonId = reason;
    },
    
    
    confirmEndDate(e) {
      console.debug(e)
      this.formData.lumpSumFormReqVO.repaymentDate = e[0];
      this.showEndCalendar = false;
    },
    
    nextStep() {
      // 表单验证
      if (!this.formData.borrowerName || this.formData.borrowerName.includes('请填写')) {
        return uni.showToast({
          title: `请选择借款方`,
          icon: 'none'
        });
      }
      
      if (!this.formData.amount) {
        return uni.showToast({
          title: '请填写欠款金额',
          icon: 'none'
        });
      }
      
      if (!this.formData.loanReasonId) {
        return uni.showToast({
          title: '请选择欠条原因',
          icon: 'none'
        });
      }
      
      if (!this.formData.borrowerIdCard) {
        return uni.showToast({
          title: '请选择借款方',
          icon: 'none'
        });
      }

      if (!this.formData.lumpSumFormReqVO.repaymentDate && this.formData.repaymentType == 0) {
        return uni.showToast({
          title: '请选择还款日期',
          icon: 'none'
        });
      }

      if (!this.formData.installmentFormReqVO.installmentCount && this.formData.repaymentType == 1) {
        return uni.showToast({
          title: '请设置分期期数',
          icon: 'none'
        });
      }

      if (!this.formData.installmentFormReqVO.installmentDays && this.formData.repaymentType == 1) {
        return uni.showToast({
          title: '请设置每期时长',
          icon: 'none'
        });
      }
      
      // 保存表单数据
      uni.setStorageSync('loanFormData', this.formData);
      
      // 跳转到确认页面
      uni.navigateTo({
        url: '/pages/loan/lender-confirm'
      });
    }
  }
}
</script>

<style lang="scss">
.loan-form-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 40rpx;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  width: 60rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  margin: 20rpx;
  padding: 0 30rpx;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  width: 160rpx;
}

.form-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.form-input {
  text-align: right;
  font-size: 30rpx;
  color: #333;
  flex: 1;
}

.unit {
  color: #999;
  font-size: 30rpx;
  margin-left: 10rpx;
}

.arrow-icon {
  margin-left: 10rpx;
}

.reason-section {
  background-color: #fff;
  border-radius: 12rpx;
  margin: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 30rpx;
}

.reason-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.reason-tag {
  padding: 15rpx 30rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.reason-tag.active {
  background-color: #1989fa;
  color: #fff;
}

.reason-input {
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  min-height: 150rpx;
}

.detailed-reason {
  width: 100%;
  height: 150rpx;
  font-size: 28rpx;
  color: #333;
}

.next-btn {
  height: 90rpx;
  background-color: #1989fa;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 20rpx;
}
</style> 